﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.Linq;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using Common.Library;

namespace ActivityTracker.Library
{
    public class History
    {
        #region Global

        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream isoStream;
        XDocument xdoc;

        #endregion

        #region Load

        public int GetLastHistoryId()
        {
            int lastHisId = 0;
            try
            {
                if (isoStore.FileExists("ActivityTracker/History.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/History.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    var ele1 = from c in xdoc.Descendants("history") orderby (int)c.Attribute("id") descending select c;
                    foreach (var varel in ele1)
                    {
                        lastHisId = Convert.ToInt32(varel.Attribute("id").Value);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in GetLastHistoryId Method In ActivityTracker.Library.History.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                ex.Data.Add("lastHisId_GetLastHistoryId", lastHisId);
                throw exNew;
            }
            return lastHisId;
        }

        public List<ActivityProp> LoadHistory(int StartIndex, int LastIndex, int count)
        {
            List<ActivityProp> RecentActs = new List<ActivityProp>();
            try
            {
                if (isoStore.FileExists("ActivityTracker/History.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/History.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    var ele = from c in xdoc.Descendants("history")
                              where (Convert.ToInt32(c.Attribute("id").Value) >= StartIndex) && (Convert.ToInt32(c.Attribute("id").Value) <= LastIndex)
                              orderby Convert.ToInt32(c.Attribute("id").Value) descending
                              select c;
                    foreach (var element in ele)
                    {
                        if (element.Element("actDur") != null)
                        {
                            ActivityProp RecentUsed = new ActivityProp();
                            RecentUsed.HisId = element.Attribute("id").Value;
                            RecentUsed.ActId = element.Element("actId").Value;
                            RecentUsed.ActName = element.Element("actName").Value;
                            RecentUsed.ActStartDate = Convert.ToDateTime(element.Element("actStartDate").Value).ToString("MM/dd/yyyy");
                            RecentUsed.ActStartTime = (element.Element("actStartTime").Value);
                            RecentUsed.ActDuration = (element.Element("actDur").Value) + " m";
                            RecentActs.Add(RecentUsed);
                        }
                    }
                }
                if (RecentActs.Count == count && StartIndex != 1)
                {
                    ActivityProp addgetmore = new ActivityProp();
                    addgetmore.ActName = "get more";
                    RecentActs.Add(addgetmore);
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in LoadHistory Method In ActivityTracker.Library.History.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("StartIndex_LoadHistory", StartIndex);
                exNew.Data.Add("LastIndex_LoadHistory", LastIndex);
                throw exNew;
            }
            return RecentActs;
        }

        public int CalDurInMins(List<LapProp> LapList, string LastLapTime)
        {
            int TotalMinutes = 0;
            try
            {
                int TotalSeconds = 0;

                if (LapList.Count > 0)
                {
                    foreach (LapProp Lp in LapList)
                    {
                        int endtimesec = Convert.ToDateTime(Lp.LapTime).Second;
                        int endtimemin = Convert.ToDateTime(Lp.LapTime).Minute;
                        int endtimehrs = Convert.ToDateTime(Lp.LapTime).Hour;

                        if (endtimehrs > 0)
                        {
                            TotalMinutes = TotalMinutes + (endtimehrs * 60);
                        }
                        if (endtimemin > 0)
                        {
                            TotalMinutes = TotalMinutes + endtimemin;
                        }
                        if (endtimesec > 0)
                        {
                            TotalSeconds = TotalSeconds + endtimesec;
                        }
                        TotalMinutes = TotalMinutes + (TotalSeconds / 60);
                    }
                }
                int Timesec = Convert.ToDateTime(LastLapTime).Second;
                int Timemin = Convert.ToDateTime(LastLapTime).Minute;
                int Timehrs = Convert.ToDateTime(LastLapTime).Hour;
                if (Timehrs > 0)
                {
                    TotalMinutes = TotalMinutes + (Timehrs * 60);
                }
                if (Timemin > 0)
                {
                    TotalMinutes = TotalMinutes + Timemin;
                }
                if (Timesec > 0)
                {
                    TotalSeconds = TotalSeconds + Timesec;
                }
                TotalMinutes = TotalMinutes + (TotalSeconds / 60);

                if (TotalMinutes == 0 && TotalSeconds > 0)
                {
                    TotalMinutes = 1;
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in CalDurInMins Method In ActivityTracker.Library.History.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                foreach (LapProp lp in LapList)
                {
                    exNew.Data.Add(lp.LapNo, lp.LapTime);
                }
                exNew.Data.Add("LastLapTime_CalDurInMins", LastLapTime);
                throw exNew;
            }
            return TotalMinutes;
        }

        #endregion

        #region Save

        public void SaveDefaultTotalDurations()
        {
            try
            {

                if (!isoStore.FileExists("ActivityTracker/TotalDurations.xml"))
                {
                    Uri uri = new Uri("DefaultData/TotalDurations.xml", UriKind.Relative);
                    xdoc = XDocument.Load(uri.ToString());
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/TotalDurations.xml", FileMode.Create, isoStore);
                    xdoc.Save(isoStream);
                    isoStream.Close();
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in SaveDefaultTotalDurations Method In ActivityTracker.Library.History.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                throw exNew;
            }
        }
        public void SaveDefaultCategoryTotalDurations()
        {
            try
            {

                if (!isoStore.FileExists("ActivityTracker/CategoryTotalDurations.xml"))
                {
                    Uri uri = new Uri("DefaultData/CategoryTotalDurations.xml", UriKind.Relative);
                    xdoc = XDocument.Load(uri.ToString());
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/CategoryTotalDurations.xml", FileMode.Create, isoStore);
                    xdoc.Save(isoStream);
                    isoStream.Close();
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in SaveDefaultTotalDurations Method In ActivityTracker.Library.History.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                throw exNew;
            }
        }

        public void SaveActivity(string actId, string actName, string actStartDate, string actStartTime)
        {
            string hisId = "0";
            try
            {
                if (!isoStore.FileExists("ActivityTracker/History.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/History.xml", FileMode.Create, isoStore);
                    xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                        new XElement("History",
                                new XElement("history", new XAttribute("id", 1),
                                    new XElement("actId", actId),
                                    new XElement("actName", actName),
                                    new XElement("actStartDate", actStartDate),
                                    new XElement("actStartTime", actStartTime))));
                    xdoc.Save(isoStream);
                    isoStream.Close();
                    hisId = "1";
                }
                else
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/History.xml", FileMode.Open, FileAccess.Read, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    hisId = (GetLastHistoryId() + 1).ToString();
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/History.xml", FileMode.Create, isoStore);
                    xdoc.Root.Add(new XElement("history", new XAttribute("id", hisId),
                             new XElement("actId", actId),
                             new XElement("actName", actName),
                             new XElement("actStartDate", actStartDate),
                             new XElement("actStartTime", actStartTime)));
                    xdoc.Save(isoStream);
                    isoStream.Close();
                }
                //saving the history id for saving geocode locations.
                SettingsHelper.Save("hisId", hisId);
                //saving LocationCount to display no of points recorded.
                SettingsHelper.Save("locCount", "1");
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in SaveActivity Method In ActivityTracker.Library.History.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("actId_SaveActivity", actId);
                exNew.Data.Add("actName_SaveActivity", actName);
                exNew.Data.Add("actStartDate_SaveActivity", actStartDate);
                exNew.Data.Add("actStartTime_SaveActivity", actStartTime);
                throw exNew;
            }
        }

        public void SaveActivityHistory(string hisId, string actEndTime, int totDur)
        {
            try
            {
                //Deleting the Running Activity file
                //if (isoStore.FileExists("RunningActivity.xml"))
                //    isoStore.DeleteFile("RunningActivity.xml");
                //saving history
                if (isoStore.FileExists("ActivityTracker/History.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/History.xml", FileMode.Open, FileAccess.Read, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    var ele = (from f in xdoc.Descendants("history") where f.Attribute("id").Value == hisId select f);
                    foreach (XElement e in ele)
                    {
                        if (e.Elements().Count() > 0)
                        {
                            e.Add(new XElement("actEndTime", actEndTime), new XElement("actDur", totDur));
                            isoStream = new IsolatedStorageFileStream("ActivityTracker/History.xml", FileMode.Create, isoStore);
                            xdoc.Save(isoStream); isoStream.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in SaveActivityHistory Method In ActivityTracker.Library.History.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("hisId_SaveActivityHistory", hisId);
                exNew.Data.Add("EndTime_SaveActivityHistory", actEndTime);
                exNew.Data.Add("TotalDuration_SaveActivityHistory", totDur);
                throw exNew;
            }
        }

        public void SaveTotalduration(string actId, string actName, int totDur, string actStartDate)
        {
            try
            {
                SaveCategoryTotalDuration(actId, actName, totDur, actStartDate);
                if (isoStore.FileExists("ActivityTracker/TotalDurations.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/TotalDurations.xml", FileMode.Open, FileAccess.Read, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    //Calculate and save Daily duration for single Activity
                    IEnumerable<XElement> Dailylist = (from ss in xdoc.Descendants("day")
                                                       where ss.Attribute("date").Value == actStartDate
                                                       select ss);
                    if (Dailylist.Count() > 0)
                    {
                        bool status = true;
                        foreach (XElement xe in Dailylist.Elements("activity").Where(x => x.Attribute("actId").Value == actId))
                        {
                            status = false;
                            xe.Attribute("totDur").Value = (totDur + Convert.ToInt32(xe.Attribute("totDur").Value)).ToString();
                            xe.Attribute("count").Value = (Convert.ToInt32(xe.Attribute("count").Value) + 1).ToString();
                            break;
                        }
                        if (status)
                        {
                            XElement elemdaily = new XElement("activity",
                            new XAttribute("actId", actId),
                            new XAttribute("actName", actName),
                            new XAttribute("totDur", totDur),
                            new XAttribute("count", 1));

                            XElement xele = (from x in xdoc.Root.Element("dailyduration").Elements()
                                                .Where(y => y.Attribute("date").Value == actStartDate)
                                             select x).Single();

                            xele.Add(elemdaily);
                            //xdoc.Root.Element("dailyduration").Element("day").Add(elemdaily);
                        }
                    }
                    else
                    {
                        XElement elemdaily12 = new XElement("day", new XAttribute("date", actStartDate),
                        new XElement("activity",
                        new XAttribute("actId", actId),
                        new XAttribute("actName", actName),
                        new XAttribute("totDur", totDur),
                        new XAttribute("count", 1)));
                        xdoc.Root.Element("dailyduration").Add(elemdaily12);
                    }
                    //Calculate and save Monthly duration for single Activity
                    string MonthName = Convert.ToDateTime(actStartDate).ToString("MMM");
                    string Monthyear = "year" + Convert.ToDateTime(actStartDate).Year.ToString();
                    if (xdoc.Descendants(Monthyear).Elements().Count() == 0)
                    {
                        XElement elem = new XElement(Monthyear,
                        new XElement(MonthName,
                        new XElement("activity",
                        new XAttribute("actId", actId),
                        new XAttribute("actName", actName),
                        new XAttribute("totDur", totDur),
                        new XAttribute("count", 1))));
                        xdoc.Root.Element("monthlyduration").Add(elem);
                    }
                    else
                    {
                        if (xdoc.Descendants(MonthName).Elements().Count() == 0)
                        {
                            XElement elem = new XElement(MonthName,
                            new XElement("activity",
                            new XAttribute("actId", actId),
                            new XAttribute("actName", actName),
                            new XAttribute("totDur", totDur),
                            new XAttribute("count", 1)));
                            xdoc.Root.Element("monthlyduration").Element(Monthyear).Add(elem);
                        }
                        else
                        {
                            bool status = true;
                            IEnumerable<XElement> year = (from years in xdoc.Descendants(Monthyear)
                                                          select years);
                            IEnumerable<XElement> vr = (from ss in year.Descendants(MonthName)
                                                        select ss);
                            foreach (XElement xe in vr.Elements("activity").Where(x => x.Attribute("actId").Value == actId))
                            {
                                status = false;
                                xe.Attribute("totDur").Value = (totDur + Convert.ToInt32(xe.Attribute("totDur").Value)).ToString();
                                xe.Attribute("count").Value = (Convert.ToInt32(xe.Attribute("count").Value) + 1).ToString();
                                break;
                            }
                            if (status)
                            {
                                XElement elem = new XElement("activity",
                                new XAttribute("actId", actId),
                                new XAttribute("actName", actName),
                                new XAttribute("totDur", totDur),
                                new XAttribute("count", 1));
                                xdoc.Root.Element("monthlyduration").Element(Monthyear).Element(MonthName).Add(elem);
                            }
                        }
                    }
                    //Calculate and save Yearly duration for single Activity
                    string dtsyear = "y" + Convert.ToDateTime(actStartDate).Year.ToString();
                    IEnumerable<XElement> yearlist = (from ss in xdoc.Descendants(dtsyear)
                                                      select ss);
                    if (yearlist.Count() > 0)
                    {
                        bool status = true;
                        foreach (XElement xe in yearlist.Elements("activity").Where(x => x.Attribute("actId").Value == actId))
                        {
                            status = false;
                            int actcount = Convert.ToInt32(xe.Attribute("count").Value);
                            int previousdur = Convert.ToInt32(xe.Attribute("totDur").Value);
                            int dura = totDur + previousdur;
                            actcount++;
                            xe.Attribute("totDur").Value = dura.ToString();
                            xe.Attribute("count").Value = actcount.ToString();
                            break;
                        }
                        if (status)
                        {
                            XElement elemyear = new XElement("activity",
                            new XAttribute("actId", actId),
                            new XAttribute("actName", actName),
                            new XAttribute("totDur", totDur),
                            new XAttribute("count", 1));
                            xdoc.Root.Element("yearlyduration").Element(dtsyear).Add(elemyear);
                        }
                    }
                    else
                    {
                        XElement elemyear = new XElement(dtsyear,
                        new XElement("activity",
                        new XAttribute("actId", actId),
                        new XAttribute("actName", actName),
                        new XAttribute("totDur", totDur),
                        new XAttribute("count", 1)));
                        xdoc.Root.Element("yearlyduration").Add(elemyear);
                    }
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/TotalDurations.xml", FileMode.Create, isoStore);
                    xdoc.Save(isoStream);
                    isoStream.Close();
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in SaveTotalduration Method In ActivityTracker.Library.History.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("actId_SaveTotalduration", actId);
                exNew.Data.Add("totDur_SaveTotalduration", totDur);
                throw exNew;
            }
        }
        public void SaveCategoryTotalDuration(string actid, string actName, int totDur, string actStartDate)
        {
            List<CategoryProp> objcatid = GettingCategoryID(actid);
            foreach (CategoryProp catid in objcatid)
            {
                savingcategoryhistory(catid.CatId, catid.catName, totDur, actStartDate);
            }
        }

        private void savingcategoryhistory(string catid, string catname, int totDur, string actStartDate)
        {
            if (isoStore.FileExists("ActivityTracker/CategoryTotalDurations.xml"))
            {
                isoStream = new IsolatedStorageFileStream("ActivityTracker/CategoryTotalDurations.xml", FileMode.Open, FileAccess.Read, isoStore);
                xdoc = XDocument.Load(isoStream);
                isoStream.Close();
                //Calculate and save Daily duration for single Activity
                IEnumerable<XElement> Dailylist = (from ss in xdoc.Descendants("day")
                                                   where ss.Attribute("date").Value == actStartDate
                                                   select ss);
                if (Dailylist.Count() > 0)
                {
                    bool status = true;
                    foreach (XElement xe in Dailylist.Elements("category").Where(x => x.Attribute("catid").Value == catid))
                    {
                        status = false;
                        xe.Attribute("totDur").Value = (totDur + Convert.ToInt32(xe.Attribute("totDur").Value)).ToString();
                        xe.Attribute("count").Value = (Convert.ToInt32(xe.Attribute("count").Value) + 1).ToString();
                        break;
                    }
                    if (status)
                    {
                        XElement elemdaily = new XElement("category",
                        new XAttribute("catid", catid),
                        new XAttribute("catname", catname),
                        new XAttribute("totDur", totDur),
                        new XAttribute("count", 1));

                        XElement xele = (from x in xdoc.Root.Element("dailyduration").Elements()
                                            .Where(y => y.Attribute("date").Value == actStartDate)
                                         select x).Single();

                        xele.Add(elemdaily);
                        //xdoc.Root.Element("dailyduration").Element("day").Add(elemdaily);
                    }
                }
                else
                {
                    XElement elemdaily12 = new XElement("day", new XAttribute("date", actStartDate),
                    new XElement("category",
                    new XAttribute("catid", catid),
                    new XAttribute("catname", catname),
                    new XAttribute("totDur", totDur),
                    new XAttribute("count", 1)));
                    xdoc.Root.Element("dailyduration").Add(elemdaily12);
                }
                //Calculate and save Monthly duration for single Activity
                string MonthName = Convert.ToDateTime(actStartDate).ToString("MMM");
                string Monthyear = "year" + Convert.ToDateTime(actStartDate).Year.ToString();
                if (xdoc.Descendants(Monthyear).Elements().Count() == 0)
                {
                    XElement elem = new XElement(Monthyear,
                    new XElement(MonthName,
                    new XElement("category",
                    new XAttribute("catid", catid),
                    new XAttribute("catname", catname),
                    new XAttribute("totDur", totDur),
                    new XAttribute("count", 1))));
                    xdoc.Root.Element("monthlyduration").Add(elem);
                }
                else
                {
                    if (xdoc.Descendants(MonthName).Elements().Count() == 0)
                    {
                        XElement elem = new XElement(MonthName,
                        new XElement("category",
                        new XAttribute("catid", catid),
                        new XAttribute("catname", catname),
                        new XAttribute("totDur", totDur),
                        new XAttribute("count", 1)));
                        xdoc.Root.Element("monthlyduration").Element(Monthyear).Add(elem);
                    }
                    else
                    {
                        bool status = true;
                        IEnumerable<XElement> year = (from years in xdoc.Descendants(Monthyear)
                                                      select years);
                        IEnumerable<XElement> vr = (from ss in year.Descendants(MonthName)
                                                    select ss);
                        foreach (XElement xe in vr.Elements("category").Where(x => x.Attribute("catid").Value == catid))
                        {
                            status = false;
                            xe.Attribute("totDur").Value = (totDur + Convert.ToInt32(xe.Attribute("totDur").Value)).ToString();
                            xe.Attribute("count").Value = (Convert.ToInt32(xe.Attribute("count").Value) + 1).ToString();
                            break;
                        }
                        if (status)
                        {
                            XElement elem = new XElement("category",
                            new XAttribute("catid", catid),
                            new XAttribute("catname", catname),
                            new XAttribute("totDur", totDur),
                            new XAttribute("count", 1));
                            xdoc.Root.Element("monthlyduration").Element(Monthyear).Element(MonthName).Add(elem);
                        }
                    }
                }
                //Calculate and save Yearly duration for single Activity
                string dtsyear = "y" + Convert.ToDateTime(actStartDate).Year.ToString();
                IEnumerable<XElement> yearlist = (from ss in xdoc.Descendants(dtsyear)
                                                  select ss);
                if (yearlist.Count() > 0)
                {
                    bool status = true;
                    foreach (XElement xe in yearlist.Elements("category").Where(x => x.Attribute("catid").Value == catid))
                    {
                        status = false;
                        int actcount = Convert.ToInt32(xe.Attribute("count").Value);
                        int previousdur = Convert.ToInt32(xe.Attribute("totDur").Value);
                        int dura = totDur + previousdur;
                        actcount++;
                        xe.Attribute("totDur").Value = dura.ToString();
                        xe.Attribute("count").Value = actcount.ToString();
                        break;
                    }
                    if (status)
                    {
                        XElement elemyear = new XElement("category",
                        new XAttribute("catid", catid),
                        new XAttribute("catname", catname),
                        new XAttribute("totDur", totDur),
                        new XAttribute("count", 1));
                        xdoc.Root.Element("yearlyduration").Element(dtsyear).Add(elemyear);
                    }
                }
                else
                {
                    XElement elemyear = new XElement(dtsyear,
                    new XElement("category",
                    new XAttribute("catid", catid),
                    new XAttribute("catname", catname),
                    new XAttribute("totDur", totDur),
                    new XAttribute("count", 1)));
                    xdoc.Root.Element("yearlyduration").Add(elemyear);
                }
                isoStream = new IsolatedStorageFileStream("ActivityTracker/CategoryTotalDurations.xml", FileMode.Create, isoStore);
                xdoc.Save(isoStream);
                isoStream.Close();
            }
        }

        private List<CategoryProp> GettingCategoryID(string actid)
        {

            List<CategoryProp> Catarr = new List<CategoryProp>();
            if (isoStore.FileExists("ActivityTracker/MyActivities.xml"))
            {
                isoStream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Open, isoStore);
                xdoc = XDocument.Load(isoStream);
                isoStream.Close();
                //Calculate and save Daily duration for single Activity
                var CatId = (from ss in xdoc.Descendants("activity")
                             where ss.Attribute("id").Value == actid
                             select ss);
                foreach (var c in CatId.Descendants("categories").Elements())
                {
                    CategoryProp cprop = new CategoryProp();
                    cprop.CatId = c.Attribute("catid").Value;
                    cprop.catName = c.Value;

                    Catarr.Add(cprop);

                }
            }

            return Catarr;
        }
        #endregion

        #region Delete

        public void DeleteHistory(string hisId)
        {
            try
            {
                DeleteGeoCodeLocations(hisId);
                DeleteTotalDuration(hisId);
                DeleteCategoryTotalDuration(hisId);
                DeleteActivityHistory(hisId);
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in DeleteHistory Method In ActivityTracker.Library.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("hisId_DeleteHistory", hisId);
                foreach (DictionaryEntry d in ex.Data)
                {
                    exNew.Data.Add(d.Key, d.Value);
                }
                throw exNew;
            }
        }

        private void DeleteCategoryTotalDuration(string hisId)
        {
            try
            {
                string actId = "";
                string startDate = "";
                int totalDuration = GetTotalDuration(hisId, out actId, out startDate);
                List<CategoryProp> objcatid = GettingCategoryID(actId);
                foreach (CategoryProp catid in objcatid)
                {
                    Deletecategoryhistory(catid.CatId, totalDuration, startDate);
                }

            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in DeleteTotalDuration Method In ActivityTracker.Library.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                foreach (DictionaryEntry d in ex.Data)
                {
                    exNew.Data.Add(d.Key, d.Value);
                }
                exNew.Data.Add("hisId_DeleteTotalDuration", hisId);
                throw exNew;
            }
        }


        private void Deletecategoryhistory(string CatId, int totalDuration, string startDate)
        {
            if (isoStore.FileExists("ActivityTracker/CategoryTotalDurations.xml"))
            {
                isoStream = new IsolatedStorageFileStream("ActivityTracker/CategoryTotalDurations.xml", FileMode.Open, isoStore);
                xdoc = XDocument.Load(isoStream);
                isoStream.Close();

                //Delete From Daily Duration
                var dailyTotDur = from t in xdoc.Descendants("day") where t.Attribute("date").Value == startDate select t;
                foreach (var dailytot in dailyTotDur.Elements().Where(x => x.Attribute("catid").Value == CatId))
                {
                    dailytot.Attribute("totDur").Value = (Convert.ToInt32(dailytot.Attribute("totDur").Value) - totalDuration).ToString();
                    dailytot.Attribute("count").Value = (Convert.ToInt32(dailytot.Attribute("count").Value) - 1).ToString();
                }

                //Delete From Monthly Duration where t.Value == Convert.ToDateTime(startDate).ToString("MMM")
                var monthlyTotDur = from t in xdoc.Descendants("year" + Convert.ToDateTime(startDate).Year) select t;
                foreach (var monthlytot in monthlyTotDur.Elements(Convert.ToDateTime(startDate).ToString("MMM")).Elements().Where(x => x.Attribute("catid").Value == CatId))
                {
                    monthlytot.Attribute("totDur").Value = (Convert.ToInt32(monthlytot.Attribute("totDur").Value) - totalDuration).ToString();
                    monthlytot.Attribute("count").Value = (Convert.ToInt32(monthlytot.Attribute("count").Value) - 1).ToString();
                }

                //Delete From Yearly Duration
                var yearlyTotDur = from t in xdoc.Descendants("y" + Convert.ToDateTime(startDate).Year) select t;
                foreach (var yearlytot in yearlyTotDur.Elements().Where(x => x.Attribute("catid").Value == CatId))
                {
                    yearlytot.Attribute("totDur").Value = (Convert.ToInt32(yearlytot.Attribute("totDur").Value) - totalDuration).ToString();
                    yearlytot.Attribute("count").Value = (Convert.ToInt32(yearlytot.Attribute("count").Value) - 1).ToString();
                }

                isoStream = new IsolatedStorageFileStream("ActivityTracker/CategoryTotalDurations.xml", FileMode.Create, isoStore);
                xdoc.Save(isoStream);
                isoStream.Close();
            }
        }

        private void DeleteTotalDuration(string hisId)
        {
            try
            {
                string actId = "";
                string startDate = "";
                int totalDuration = GetTotalDuration(hisId, out actId, out startDate);
                if (isoStore.FileExists("ActivityTracker/TotalDurations.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/TotalDurations.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();

                    //Delete From Daily Duration
                    var dailyTotDur = from t in xdoc.Descendants("day") where t.Attribute("date").Value == startDate select t;
                    foreach (var dailytot in dailyTotDur.Elements().Where(x => x.Attribute("actId").Value == actId))
                    {
                        dailytot.Attribute("totDur").Value = (Convert.ToInt32(dailytot.Attribute("totDur").Value) - totalDuration).ToString();
                        dailytot.Attribute("count").Value = (Convert.ToInt32(dailytot.Attribute("count").Value) - 1).ToString();
                    }

                    //Delete From Monthly Duration where t.Value == Convert.ToDateTime(startDate).ToString("MMM")
                    var monthlyTotDur = from t in xdoc.Descendants("year" + Convert.ToDateTime(startDate).Year) select t;
                    foreach (var monthlytot in monthlyTotDur.Elements(Convert.ToDateTime(startDate).ToString("MMM")).Elements().Where(x => x.Attribute("actId").Value == actId))
                    {
                        monthlytot.Attribute("totDur").Value = (Convert.ToInt32(monthlytot.Attribute("totDur").Value) - totalDuration).ToString();
                        monthlytot.Attribute("count").Value = (Convert.ToInt32(monthlytot.Attribute("count").Value) - 1).ToString();
                    }

                    //Delete From Yearly Duration
                    var yearlyTotDur = from t in xdoc.Descendants("y" + Convert.ToDateTime(startDate).Year) select t;
                    foreach (var yearlytot in yearlyTotDur.Elements().Where(x => x.Attribute("actId").Value == actId))
                    {
                        yearlytot.Attribute("totDur").Value = (Convert.ToInt32(yearlytot.Attribute("totDur").Value) - totalDuration).ToString();
                        yearlytot.Attribute("count").Value = (Convert.ToInt32(yearlytot.Attribute("count").Value) - 1).ToString();
                    }

                    isoStream = new IsolatedStorageFileStream("ActivityTracker/TotalDurations.xml", FileMode.Create, isoStore);
                    xdoc.Save(isoStream);
                    isoStream.Close();
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in DeleteTotalDuration Method In ActivityTracker.Library.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                foreach (DictionaryEntry d in ex.Data)
                {
                    exNew.Data.Add(d.Key, d.Value);
                }
                exNew.Data.Add("hisId_DeleteTotalDuration", hisId);
                throw exNew;
            }
        }

        private void DeleteActivityHistory(string hisId)
        {
            try
            {
                if (isoStore.FileExists("ActivityTracker/History.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/History.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    (from f in xdoc.Descendants("history") where f.Attribute("id").Value == hisId select f).Remove();
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/History.xml", FileMode.Create, isoStore);
                    xdoc.Save(isoStream);
                    isoStream.Close();
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in DeleteActivityHistory Method In ActivityTracker.Library.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("hisId_DeleteActivityHistory", hisId);
                throw exNew;
            }
        }

        private void DeleteGeoCodeLocations(string hisId)
        {
            try
            {
                string filename = "ActivityTracker/Location_" + hisId.ToString() + ".xml";
                if (isoStore.FileExists(filename))
                    isoStore.DeleteFile(filename);
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in DeleteGeoCodeLocations Method In ActivityTracker.Library.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("hisId_DeleteGeoCodeLocations", hisId);
                throw exNew;
            }
        }

        private int GetTotalDuration(string hisId, out string actId, out string startDate)
        {
            int totalDuration = 0;
            actId = "";
            startDate = "";
            try
            {
                if (isoStore.FileExists("ActivityTracker/History.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/History.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    var totDur = from t in xdoc.Descendants("history") where t.Attribute("id").Value == hisId select t;
                    foreach (var tot in totDur)
                    {
                        totalDuration = Convert.ToInt32(tot.Element("actDur").Value);
                        actId = tot.Element("actId").Value;
                        startDate = tot.Element("actStartDate").Value;
                    }
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in GetTotalDuration Method In ActivityTracker.Library.History file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("hisId_GetTotalDuration", hisId);
                throw exNew;
            }
            return totalDuration;
        }


        #endregion
    }
}
